package com.hy.service.impl;

import com.hy.bean.*;
import com.hy.dao.*;
import com.hy.dao.impl.*;
import com.hy.dto.CarDto;
import com.hy.exception.BizException;
import com.hy.service.CarpartstableService;
import com.hy.utils.DBManager;
import com.hy.vo.CarpartstableVo;
import org.apache.commons.dbutils.DbUtils;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CarpartstableServiceImpl implements CarpartstableService {
    private CarpartstableDao carpartstableDao = new CarpartstableDaoImpl();
    private final BuytableDao buytableDao = new BuytableDaoImpl();

    private final BuyParttableDao buyParttableDao = new BuyParttableDaoImpl();

    @Override
    public List<Carpartstable> select(String code, String beginDate, String endDate, String creator) {
        return carpartstableDao.select(code, beginDate, endDate, creator);
    }

    @Override
    public PageResult queryAll(Integer currPage, Integer pageSize, CarDto carDto) {
        List<CarpartstableVo> carpartstableVos = carpartstableDao.selectAll(currPage, pageSize, carDto);
        Long county = carpartstableDao.county(carDto);
        return new PageResult(carpartstableVos, county, currPage, pageSize);
    }

    @Override
    public List<Carpartstable> select() {
        return carpartstableDao.select();
    }

    @Override
    public RespBean queryAllByLimit(Integer limit, Integer page) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", carpartstableDao.queryAllByLimit(limit, page));
        map.put("total", carpartstableDao.count());
        return RespBean.success("查询成功", map);
    }

    @Override
    public RespBean save(Carpartstable carpartstable) {
        Connection connection = null;
        Boolean flag = false;
        try {
            connection = DBManager.getConnection();
            connection.setAutoCommit(false);

            //添加零件
            int insert = carpartstableDao.insert(connection, carpartstable);
            //添加采购
            Integer buytableId = 0;
            //根据当前时间查询 当前时间是否有采购
            Buytable buytableIsNull = buytableDao.selectByRequestTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            if (buytableIsNull == null) {
                //创建采购表
                Buytable buytable = new Buytable(
                        null, Integer.parseInt(randomGenerate()), null, null, null, carpartstable.getPartcreater(), carpartstable.getPartcreatedate(), null, null, null, null, null, null, null, null, 0.0, "2", "采购新品"
                );
                //添加采购
                buytableId = buytableDao.insert(connection, buytable);
            } else {
                buytableId = buytableIsNull.getId();
            }

            BuyParttable buyParttable = new BuyParttable(null, buytableId, insert, carpartstable.getPartstore(), 0, 0, 0.0, 0.0);
            buyParttable.setTotalprice((double) (carpartstable.getCostprice() * buyParttable.getBuycount()));
            //添加采购中间表
            int buyParttableId_notEnough = buyParttableDao.insert(connection, buyParttable);
            connection.commit();
            Double zje = buyParttableDao.selectsumzj(buytableId);
            int updateBuyerAndBuyTimeById = buytableDao.updateBuyerAndBuyTimeById(connection, buytableId, null, null, zje);
            connection.commit();
            flag = true;
        } catch (Exception e) {
            try {
                flag = false;
                connection.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new BizException("添加失败");
        } finally {
            try {
                DbUtils.close(connection);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return flag ? RespBean.success("添加成功") : RespBean.error("添加失败");
    }

    private String randomGenerate() {
        String datastr = "";
        Integer randomNumber = 0;
        Integer v = (int) (Math.floor(Math.random() * (10 - 5 + 1)) + 5);
        for (int i = 0; i < v; i++) {
            if (i % 2 == 0) {
                randomNumber = (int) Math.floor(Math.random() * 10);
                datastr += randomNumber + "";
            } else {
                randomNumber = (int) Math.floor(Math.random() * 5);
                datastr += randomNumber + "";
            }
        }
        return datastr;
    }
}